﻿using MediatR;
using Medical.Api.Read.Application.Command.RecyclingCleaning.Disinfects;
using Medical.Domain.RecoveryCleaning;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Microsoft.EntityFrameworkCore;

namespace Medical.Api.Read.Application.Handler.RecyclingCleaning.Disinfects
{
    /// <summary>
    /// 获取待消毒列表的命令处理
    /// </summary>
    public class GetDisinfectedListCommandHandlter : IRequestHandler<GetDisinfectedListCommand, ApiResult<List<DisinfectionRegistration>>>
    {
        /// <summary>
        /// 消毒登记仓储
        /// </summary>
        private readonly IBaseRepository<DisinfectionRegistration> _disinfectionRegistrationRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="disinfectionRegistrationRepository">消毒登记仓储</param>
        public GetDisinfectedListCommandHandlter(IBaseRepository<DisinfectionRegistration> disinfectionRegistrationRepository)
        {
            _disinfectionRegistrationRepository = disinfectionRegistrationRepository;
        }

        /// <summary>
        /// 处理获取待消毒列表的请求
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>待消毒列表</returns>
        public async Task<ApiResult<List<DisinfectionRegistration>>> Handle(GetDisinfectedListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查询所有未删除且状态为未完成的消毒登记记录
                var query = _disinfectionRegistrationRepository.GetAll()
                    .Where(x => !x.IsDeleted && x.Status == 0) // Status = 0 表示未完成
                    .OrderByDescending(x => x.StartTime); // 按开始时间降序排序

                // 执行查询
                var result = query.ToList();

                return new ApiResult<List<DisinfectionRegistration>>
                {
                    Code = ApiEnums.Success,
                    Msg = "获取待消毒列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<DisinfectionRegistration>>
                {
                    Code = ApiEnums.Error,
                    Msg = $"获取待消毒列表异常：{ex.Message}",
                    Data = null
                };
            }
        }
    }
}
